package net.myspring.common.thymeleaf.function.dialect;

import net.myspring.common.thymeleaf.function.expression.ThymeleafFunction;
import org.thymeleaf.context.IExpressionContext;
import org.thymeleaf.expression.IExpressionObjectFactory;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class ThymeleafFunctionExpressionFactory implements IExpressionObjectFactory {

    private static final String THYMELEAF_FUNCTION_EVALUATION_VARIABLE_NAME = "fn";

    private static final Set<String> ALL_EXPRESSION_OBJECT_NAMES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(THYMELEAF_FUNCTION_EVALUATION_VARIABLE_NAME)));

    @Override
    public Set<String> getAllExpressionObjectNames() {
        return ALL_EXPRESSION_OBJECT_NAMES;
    }

    @Override
    public Object buildObject(IExpressionContext context, String expressionObjectName) {
        if (THYMELEAF_FUNCTION_EVALUATION_VARIABLE_NAME.equals(expressionObjectName)) {
            return new ThymeleafFunction();
        }
        return null;
    }

    @Override
    public boolean isCacheable(String expressionObjectName) {
        return expressionObjectName != null && THYMELEAF_FUNCTION_EVALUATION_VARIABLE_NAME.equals(expressionObjectName);
    }

}
